package com.example.sens.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.example.sens.service.IStorageService;
import com.example.sens.utils.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
@Scope("prototype")
public class FileUploadController {

    private final IStorageService storageService;

    @Autowired
    public FileUploadController(IStorageService storageService) {
        this.storageService = storageService;
    }

    @PostMapping("/fileupload")
    @ResponseBody
    public Response<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        Response<String> result = new Response<String>();
        // 保存文件
        String path = storageService.store(file);

        result.setSuccess(true);
        path=path.replaceAll("\\\\", "/");
        result.setData(path);
        return result;
    }

    @PostMapping("/filesupload")
    @ResponseBody
    public Response<List<String>> handleFileUpload(@RequestParam("file") List<MultipartFile> files) {
        Response<List<String>> result = new Response<>();
        // 保存文件
        List<String> paths = new ArrayList<>();
        files.forEach(file -> {
            String path = storageService.store(file);
            path=path.replaceAll("\\\\", "/");
            paths.add(path);
        });

        result.setSuccess(true);
        result.setData(paths);
        return result;
    }

    @GetMapping("/files/{basepath}/{typepath}/{yearpath}/{monthpath}/{daypath}/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String typepath, @PathVariable String yearpath, @PathVariable String monthpath,
                                              @PathVariable String daypath, @PathVariable String filename) {

        String filepath = typepath + "/" + yearpath + "/" + monthpath + "/" + daypath + "/" + filename;
        Resource file = storageService.loadAsResource(filepath);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

    /**
     * 根据传来名字返回修改名字后的文件
     * @param typepath
     * @param yearpath
     * @param monthpath
     * @param daypath
     * @param filename
     * @param name
     * @return
     */
    @GetMapping("/files/{basepath}/{typepath}/{yearpath}/{monthpath}/{daypath}/{filename:.+}/{name}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String typepath, @PathVariable String yearpath, @PathVariable String monthpath,
                                              @PathVariable String daypath, @PathVariable String filename,@PathVariable(required = false) String name) throws UnsupportedEncodingException {
        String filepath = typepath + "/" + yearpath + "/" + monthpath + "/" + daypath + "/" + filename;
        Resource file = storageService.loadAsResource(filepath);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + (StringUtils.isBlank(name)?file.getFilename():URLEncoder.encode(name, "utf-8").replace("+", "%20")) + "\"").body(file);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleStorageFileNotFound(Exception exc) {
        return ResponseEntity.notFound().build();
    }

}
